# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=cjson
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.7.18
pkgrel=1
pkgdesc="Ultralightweight JSON parser in ANSI C (mingw-w64)"
arch=(any)
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/DaveGamble/cJSON"
msys2_references=(
  "cpe: cpe:/a:cjson_project:cjson"
)
license=('spdx:MIT')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/DaveGamble/cJSON/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-cmake-files.patch")
sha256sums=('3aa806844a03442c00769b83e99970be70fbef03735ff898f4811dd03b9f5ee5'
            'f7a5e88c13d58806876dac5d2e255812bee7837cfe7214c9fe8e0f57edb5c25d')

prepare() {
  cd ${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-cmake-files.patch
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G Ninja \
    "${_extra_config[@]}" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DENABLE_CJSON_TEST=OFF \
    -DBUILD_SHARED_AND_STATIC_LIBS=ON \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    -DENABLE_CJSON_UTILS=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

  for pcfile in  "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${MINGW_PREFIX}|\${prefix}|g" -i "${pcfile}"
    sed -i "1s|^|prefix=${MINGW_PREFIX}\\n|" "${pcfile}"
  done

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
